#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iconv.h>
#include <errno.h>

/**********************************************************
 * 描述: 创建字符集转换的描述符
 * 输入: fromcode	原字符集
 *       tocode		目的字符集
 * 返回: 转换句柄
 * ********************************************************/

iconv_t get_code_fd(const char *tocode, const char *fromcode)
{
	iconv_t cd = iconv_open(tocode, fromcode);
	if (cd == (iconv_t)-1)
	{
		printf("iconv_open %s to %s error: %s\n", fromcode, tocode, strerror(errno));
	}

	return cd;
}

/**********************************************************
 * 描述: 字符集转换接口
 * 输入: cd				字符集描述符
 *       inbuf			输入缓冲区
 *       inbytesleft	输入缓冲区长度
 *       outbuf			输出缓冲区
 *       outbytesleft	输出缓冲区长度
 * 返回: >= 0: 返回输出字符串长度; < 0: 错误
 * ********************************************************/

int convcharset(iconv_t cd,
				char *inbuf, size_t *inbytesleft,
				char *outbuf, size_t *outbytesleft)
{
	size_t outbuflen = *outbytesleft;
	size_t nret = iconv(cd, (char **)&inbuf, inbytesleft, (char **)&outbuf, outbytesleft);
	if (nret == (size_t)-1)
	{
		printf("iconv error: %s\n", strerror(errno));

		return -1;
	}

	return (int)(outbuflen - *outbytesleft);
}

/**********************************************************
 * 描述: 关闭字符集转换的描述符
 * 输入: cd	需要关闭的描述符
 * 返回: 0: 成功; -1: 错误
 * ********************************************************/

int close_code_fd(iconv_t cd)
{
	return iconv_close(cd);
}

int main(void)
{
	iconv_t convfd = (iconv_t)-1;;

	char inbuf[20] = "四川名山";
	size_t inlen = strlen(inbuf);

	char *outbuf = (char *)malloc(20);
	size_t outlen = 20;

	convfd = get_code_fd("GB2312", "UTF-8");
	int len = convcharset(convfd, inbuf, &inlen, outbuf, &outlen);
	printf("outbuf: [%s]\n", outbuf);
	printf("ret len: %d\n", len);

	free(outbuf);
	outbuf = NULL;

	return 0;
}

